﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;
using BLL;
using CrystalDecisions.CrystalReports.Engine;
using Model;

namespace ProductionAnalysis.Web
{
    public partial class ViewTest_ViewTestItem : System.Web.UI.Page
    {
        private ReportDocument doc = new ReportDocument();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //this.GridView1.Attributes.Add("SortExpression", "TestItemName");
                //this.GridView1.Attributes.Add("SortDirection", "ASC");
                
                //显示报表总页数
                this.CrystalReportViewer1.ShowLastPage();
                this.CrystalReportViewer1.ShowFirstPage();
                BindTestItem();
                Check();
                this.Page.Unload+=new EventHandler(Page_Unload);
            }
        }

        private void Check()
        {
            if (HttpContext.Current != null)
            {
                if (Roles.IsUserInRole("Manager")||Roles.IsUserInRole("Administrators"))
                {
                    this.HyperLink3.Enabled = true;
                }
            }
        }

        protected void BindTestItem()
        {
            TestItem testItem = new TestItem();            
            string str1 = (string)Session["productSN"];
            DateTime dt1 =(DateTime)Session["testTime"];
            if (str1 != null)
            {
                // 获取GridView排序数据列及排序方向
                //string sortExpression = this.GridView1.Attributes["SortExpression"];
                //string sortDirection = this.GridView1.Attributes["SortDirection"];

                //DataTable dtBind = (DataTable)testItem.GetTestItems(str1, dt1);

                //// 根据GridView排序数据列及排序方向设置显示的默认数据视图
                //if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
                //{
                //    dtBind.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
                //}
                GridView1.DataSource = testItem.GetTestItems(str1, dt1);
                GridView1.DataBind();
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    if (GridView1.Rows[i].Cells[11].Text == "Fail")
                        GridView1.Rows[i].Cells[11].ForeColor = System.Drawing.Color.Red;
                }
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            BindTestItem();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Test test = new Test();
            TestItem testItem = new TestItem();
            string str1 = (string)Session["productSN"];
            DateTime dt1 = (DateTime)Session["testTime"];
            TestInfo testinfo = test.GetTest(str1, dt1);
            List<TestItemInfo> testiteminfos = (List<TestItemInfo>)testItem.GetTestItems(str1, dt1);

            //SaveFileDialog sfd = new SaveFileDialog();
            //sfd.Filter = "txt文件|*.txt";
            //sfd.Title = "保存测试数据";
            //sfd.ShowDialog();


            //if (sfd.FileName != "")
            //{
            if (!Directory.Exists(Server.MapPath(".") + "\\测试数据"))
            {
                DirectoryInfo d = Directory.CreateDirectory(Server.MapPath(".") + "\\测试数据");
            }
            string filename = Server.MapPath(".") + "\\测试数据\\" + testinfo.ProductSN + " " + testinfo.TestTime.ToString("yyyyMMddHHmm") + ".csv";//.Year + testinfo.TestTime.Month + testinfo.TestTime.Day + " " + testinfo.TestTime.Hour + testinfo.TestTime.Minute + ".txt";
            using (StreamWriter sw = File.CreateText(filename))
            {
                sw.WriteLine(testinfo.ProductSN + ",    " + testinfo.TestTime + ",  " + testinfo.ProductTypeID + ",   " + testinfo.UserID + ",   " + testinfo.ENAID + ",    " + testinfo.IsSwitch + ",  " + testinfo.IsPass);
                sw.WriteLine();
                sw.WriteLine("TestItemName,ProductSN,Testime,MeasType,StartF,StopF,Max,Min,HighSpec,LowSpec,IsPass");
                foreach (TestItemInfo tii in testiteminfos)
                {
                    sw.WriteLine(tii.TestItemName + ",  " + tii.ProductSN + ",  " + tii.TestTime + ",   " + tii.TestTypeID + ", " + tii.StartF + ", " + tii.StopF + ",  " + tii.Max + ",    " + tii.Min + ",    " + tii.HighSpec + ",   " + tii.LowSpec + ",    " + tii.IsPass);
                }
                sw.Close();
            }
            //}
            this.DownLoadFile(filename);
        }

        private void DownLoadFile(string fileName)
        {
            string filePath = fileName;
            if (File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码    
                Response.AddHeader("Content-length", file.Length.ToString());
                Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
        }


        //排序 
        //protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        //{
        //    string sortExpression = e.SortExpression.ToString();

        //    // 假定为排序方向为“顺序”
        //    string sortDirection = "ASC";

        //    // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
        //    if (sortExpression == this.GridView1.Attributes["SortExpression"])
        //    {
        //        //获得下一次的排序状态
        //        sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        //    }

        //    // 重新设定GridView排序数据列及排序方向
        //    this.GridView1.Attributes["SortExpression"] = sortExpression;
        //    this.GridView1.Attributes["SortDirection"] = sortDirection;

        //    this.BindTestItem();
        //}

        public IList<TestItemInfo> GetData()
        {
            IList<TestItemInfo> testItems = new List<TestItemInfo>();
            TestItem testItem = new TestItem();
            string str1 = (string)Session["productSN"];
            DateTime dt1 = (DateTime)Session["testTime"];
            testItems = testItem.GetTestItems(str1, dt1);
            return testItems;
        }

        protected void CrystalReportViewer1_Init(object sender, EventArgs e)
        {
            ForCrystalReport();
        }

        protected void ForCrystalReport()
        {
            doc.Load(Server.MapPath("ViewTestItem.rpt"));
            //doc = new CrystalReport1();

            TextObject txtProductSN = (TextObject)doc.ReportDefinition.ReportObjects["Text4"];
            txtProductSN.Text = "腔体序列号：" + (string)Session["productSN"];
            TextObject txtTestTime = (TextObject)doc.ReportDefinition.ReportObjects["Text13"];
            txtTestTime.Text = "测试时间：" + ((DateTime)Session["testTime"]).ToString();
            TextObject txtProductTypeID = (TextObject)doc.ReportDefinition.ReportObjects["Text14"];
            txtProductTypeID.Text = "产品类型：" + (string)Session["ProductTypeID"];
            TextObject txtUserID = (TextObject)doc.ReportDefinition.ReportObjects["Text15"];
            txtUserID.Text = "测试员工号：" + (string)Session["UserID"];
            TextObject txtENAID = (TextObject)doc.ReportDefinition.ReportObjects["Text16"];
            txtENAID.Text = "矢网编号：" + (string)Session["ENAID"];
            TextObject txtSpecVersion = (TextObject)doc.ReportDefinition.ReportObjects["Text2"];
            txtSpecVersion.Text = "指标单版本：" + (string)Session["SpecVersion"];
            TextObject txtIsPass = (TextObject)doc.ReportDefinition.ReportObjects["Text17"];
            txtIsPass.Text = "是否通过：" + (string)Session["IsPass"];

            //TextObject txtTitle = (TextObject)doc.ReportDefinition.ReportObjects["txtTitle"];
            //txtTitle.Text += "相当不错";

            IList<TestItemInfo> list = GetData();
            doc.SetDataSource(list);
            this.CrystalReportViewer1.ReportSource = doc;
        }

        private void Page_Unload(object sender, EventArgs e)
        {
            doc.Dispose();
        }
    }
}